const News = require('../models/News');
const User = require('../models/User');
const Banner = require("../models/Banner");

//首页综合数据
exports.getComprehensiveData = async function (req, res, next) {
  //用户数
  let userTotal = await User.find().count()

  //新闻数
  let newsTotal = await News.find().count()

  //  轮播图数
  let bannnerTotal = await Banner.find().count()

  try {
    res.send({
      code: 20000,
      data: {
        userTotal: userTotal || 0,
        newsTotal: newsTotal || 0,
        bannnerTotal: bannnerTotal || 0
      },
      message: '查询成功'
    })
  } catch (e) {
    console.log("-> e", e);
  }
}


//图表数据
exports.chartData = async function (req, res, next) {
  //新闻
  let newsData = await News.aggregate([
    {
      $project: {date: {$dateToString: {format: '%Y-%m-%d', date: '$updatedAt'}}},
    },
    {$group: {_id: '$date', newsCount: {$sum: 1}}},
    {$project: {date: '$_id', _id: 0, newsCount: 1}}, // 再使用$project将_id改名为date
    {$sort: {date: -1}}, // 根据日期倒序
    {
      $limit: 7
    }
  ])
//轮播图
  let bannerData = await Banner.aggregate([
    {
      $project: {date: {$dateToString: {format: '%Y-%m-%d', date: '$date'}}},
    },
    {$group: {_id: '$date', bannerCount: {$sum: 1}}},
    {$project: {date: '$_id', _id: 0, bannerCount: 1}}, // 再使用$project将_id改名为date
    {$sort: {date: -1}}, // 根据日期倒序
    {
      $limit: 7
    }
  ])
  console.log("-> bannerData", bannerData);

  var allData = [...newsData, ...bannerData]
  var dateArr = allData.map(item => {
    return item.date
  })
  dateArr = [...new Set(dateArr)]
  var data = dateArr.map(item => {
    let newsCount = newsData.find(i => {
      return i.date == item
    })?.newsCount || 0
    let bannerCount = bannerData.find(i => {
      return i.date == item
    })?.bannerCount || 0
    return {
      date: item,
      newsCount,
      bannerCount
    }
  })
  try {
    res.send({
      code: 20000,
      data,
      message: '查询成功'
    })
  } catch (e) {
    console.log("-> e", e);
  }
}
